package com.jrzh.config;

import java.security.KeyPair;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
/**
 * OAuth2服务端配置
 * 使用注解@EnableAuthorizationServer来企业OAutn2的认证服务器功能
 * @author Xanthin
 *
 */
@Configuration
@EnableAuthorizationServer
public class OAuthConfigurer extends AuthorizationServerConfigurerAdapter {

	//使用项目的数字证书并设置了密码和别名等参数
	@Bean
	public JwtAccessTokenConverter jwtAccessTokenConverter(){
		JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
		KeyPair keyPair = new KeyStoreKeyFactory(new ClassPathResource("keystore.jks"),"tc123456".toCharArray()).getKeyPair("tycoonclient");
		converter.setKeyPair(keyPair);
		return converter;
	}
	
	/**
	 * 设定OAuth2客户端ID为ssoclient，密钥为ssosecret
	 * 注意autoApprove(true)设定了自动确认授权，这样用户登录后，不再需要进行一次授权确认操作
	 */
	@Override
	public void configure(ClientDetailsServiceConfigurer clients)throws Exception {
		clients.inMemory().withClient("ssoclient").secret("ssosecret")
		.autoApprove(true)
		.authorizedGrantTypes("authorization_code","refresh_token").scopes("openid");
	}
	
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints)throws Exception {
		endpoints.accessTokenConverter(jwtAccessTokenConverter());
	}
	
	@Override
	public void configure(AuthorizationServerSecurityConfigurer security)throws Exception {
		security.
		tokenKeyAccess("permitAll()").
		checkTokenAccess("isAuthenticated()").
		allowFormAuthenticationForClients();
	}
}
